package kontrol;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import database.DALException;
import database.MySQLProduktBatchDAO;
import database.MySQLProduktBatchKompDAO;
import database.MySQLRaavareDAO;
import database.MySQLReceptDAO;
import database.MySQLReceptKompDAO;
import database.ProduktBatchDAO;
import database.ProduktBatchDTO;
import database.ProduktBatchKompDAO;
import database.ProduktBatchKompDTO;
import database.RaavareDAO;
import database.RaavareDTO;
import database.ReceptDAO;
import database.ReceptKompDAO;
import database.ReceptKompDTO;

/**
 * Servlet implementation class Product
 */
@WebServlet({ "/Productbatch", "/Productbatch/*", "/Productbatchkomp", "/Productbatchkomp/*" })
public class Productbatch extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Productbatch() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
			if (request.getRequestURI()
					.endsWith("Productbatch/AddProductbatch")) {
				request.setAttribute("message", " ");
				request.getRequestDispatcher("/WEB-INF/productbatch/createproductbatch.jsp").forward(request, response);
			} else if (request.getRequestURI().endsWith(			// den vil ikke vidersende til showproductbatchkomp.jsp
					"Productbatchkomp/ShowProductbatchkomp")) {
				
				MySQLProduktBatchKompDAO pbkDTO = null;
				try {
					pbkDTO = new MySQLProduktBatchKompDAO();
					request.setAttribute("count", pbkDTO.getCount());
				} catch (DALException e) {
					request.setAttribute("count", 0);
				}
				if (((Integer) request.getAttribute("count")) < 10) {
					try {
						List<ProduktBatchKompDTO> liste = pbkDTO.getProduktBatchKompList();
						String results = "<table border=\"1\"> <tr> <th>pbId </th> <th>Netto</th> <th>Tara</th> <th>OprId</th> <th>RbId</th> </tr>";
						for (int i = 0; i < liste.size(); i++) {
							results += "<tr> <td>" + liste.get(i).getPbId()
									+ "</td><td> " + liste.get(i).getNetto()
									+ "</td><td> " + liste.get(i).getTara()
									+ "</td><td> " + liste.get(i).getOprId()
									+ "</td><td> " + liste.get(i).getRbId()
									+ "<br>" + "</td> </tr>";
						}
						 results += "</table>";
						request.setAttribute("results", results);
					} catch (DALException e) {
						e.printStackTrace();
					}
				} else {
					if (session.getAttribute("page") != null) {
						session.setAttribute("page", 0);
					}
					int curPage = Integer.getInteger((String) session
							.getAttribute("page"));
					List<ProduktBatchKompDTO> liste;
					try {
						liste = pbkDTO
								.getProduktBatchKompList(curPage, 10);
						String results = "<table border=\"1\"> <tr> <th>pbId </th> <th>Netto</th> <th>Tara</th> <th>OprId</th> <th>RbId</th> </tr>";
					for (int i = 0; i < liste.size(); i++) {

						results += "<tr> <td>" + liste.get(i).getPbId()
								+ "</td><td> " + liste.get(i).getNetto()
								+ "</td><td> " + liste.get(i).getTara()
								+ "</td><td> " + liste.get(i).getOprId()
								+ "</td><td> " + liste.get(i).getRbId()
								+ "<br>" + "</td> </tr>";
					}
					results += "</table>";
					request.setAttribute("results", results);
					} catch (DALException e) {
						e.printStackTrace();
						}
					}
				request.getRequestDispatcher(
						"/WEB-INF/productbatchkomp/showproductbatchkomp.jsp").forward(
						request, response);
			} else if (request.getRequestURI().endsWith(
					"Productbatch/ShowProductbatch")) {
				MySQLProduktBatchDAO pbDTO = null;
				try {
					pbDTO = new MySQLProduktBatchDAO();
					request.setAttribute("count", pbDTO.getCount());
				} catch (DALException e) {
					e.printStackTrace();
					request.setAttribute("count", 0);
				}
				if (((Integer) request.getAttribute("count")) < 10) {
					try {
						List<ProduktBatchDTO> liste = pbDTO
								.getProduktBatchList();
						String results = "<table border=\"1\"> <tr> <th>pbId </th> <th>receptId</th> <th>status1</th> </tr>";
						for (int i = 0; i < liste.size(); i++) {
							results += "<tr> <td>" + liste.get(i).getPbId()
									+ "</td><td> " + liste.get(i).getReceptId()
									+ "</td><td> " + liste.get(i).getStatus()
									+ "<br>" + "</td> </tr>";

						}
						 results += "</table>";
						request.setAttribute("results", results);
					} catch (DALException e) {

						e.printStackTrace();
					}
				} else {
					if (request.getAttribute("page") == null) {
						request.setAttribute("page", 0);
					}
					if (request.getParameter("p") != null) {
						request.setAttribute("page", Integer.parseInt(request.getParameter("p")));
					}
					int curPage = (Integer) request.getAttribute("page");
					try {
						List<ProduktBatchDTO> liste = pbDTO
								.getProduktBatchList(curPage, 10);
						String results = "<table border=\"1\"> <tr> <th>pbId</th> <th>receptId</th> <th>status1</th> </tr>";
						for (int i = 0; i < liste.size(); i++) {

							results += "<tr> <td>"
									+ liste.get(i).getPbId() + "</td><td> "
									+ liste.get(i).getReceptId() + "</td><td> "
									+ liste.get(i).getStatus() + "<br>"
									+ "</td> </tr>";
						}
						results += "</table>";
						if (curPage > 9) {
							results += "<a href=\"?p=" + (curPage - 10) + "\">Prev</a>&nbsp;&nbsp;&nbsp;";
						}
						if ((((Integer) request.getAttribute("count")) - 10) > curPage) {
							results += "<a href=\"?p=" + (curPage + 10) + "\">Next</a>";
						}						
						
						request.setAttribute("results", results);
					} catch (DALException e) {

						e.printStackTrace();
					}
				}
				request.getRequestDispatcher(
						"/WEB-INF/productbatch/showproductbatch.jsp").forward(
						request, response);
			} else if (request.getRequestURI().endsWith(
					"Productbatch/ProductbatchHome")) {
				request.getRequestDispatcher(
						"/WEB-INF/productbatch/productbatchhome.jsp").forward(
						request, response);		
			} else if (request.getRequestURI().endsWith(
					"Productbatch/ProductbatchPrint")) {
				List<ProduktBatchDTO> batchlist = null;
				try {
					ProduktBatchDAO productb = new MySQLProduktBatchDAO();
					batchlist = productb.getProduktBatchList();
				} catch (DALException e) {	}
				if (batchlist != null) {
					String list = "";
					for (int i = 0; i<batchlist.size(); i++) {
						list += "<option value=\"" + batchlist.get(i).getPbId() + "\">" + batchlist.get(i).getPbId() + "</option>";
					}
					request.setAttribute("productbatchlist", list);
				}
				request.getRequestDispatcher(
						"/WEB-INF/productbatch/productbatchprint.jsp").forward(
						request, response);			
			} else if (request.getRequestURI().endsWith(
					"Productbatch/ProductbatchPrintView")) {
				response.setHeader("Content-type", "text/plane");
				PrintWriter out = response.getWriter();
				int id = 0;
				try {
					id = Integer.parseInt(request.getParameter("id"));
				} catch (NumberFormatException e) {
					out.println("Error fetching the prodoction batch id.");
				}
				ProduktBatchDAO productBatchDAO;
				try {
					productBatchDAO = new MySQLProduktBatchDAO();
					ProduktBatchDTO pb = productBatchDAO.getProduktBatch(id);
					RaavareDAO raavareDAO = new MySQLRaavareDAO();
					ReceptKompDAO komp = new MySQLReceptKompDAO();
					Calendar cal = Calendar.getInstance();
					String timeStamp = new SimpleDateFormat("dd-MM-yy").format(cal.getTime());
					out.println("Udskrevet\t" + timeStamp);
					out.println("Produkt Batch nr.\t" + String.format("%08d", pb.getPbId()));
					out.println("Recept nr.\t" + String.format("%08d", pb.getReceptId()));
					out.println("\n________________________________________________________________________________\n");
										
					List<ReceptKompDTO> kompListe = komp.getReceptKompList(pb.getReceptId());
					for (int i = 0; i < kompListe.size(); i++) {
						out.println("Råvare nr.   " + String.format("%08d", kompListe.get(i).getRaavareId()));
						RaavareDTO raavareKomponent = raavareDAO.getRaavare(kompListe.get(i).getRaavareId());
						String raavareNavn = raavareKomponent.getRaavareNavn();
						out.println("Råvare navn: " + raavareNavn);
						out.println("\n--------------------------------------------------------------------------------");
						out.print(" Del      ");
						out.print(" Mængde   ");
						out.print(" Tolerence");
						out.print(" Tara     ");
						out.print(" Netto(kg)");
						out.print(" Batch    ");
						out.print(" Opr.     ");
						out.print(" Terminal \n");
						
						out.print(" 1        ");	
						out.print(" " + String.format("%.3f   ", kompListe.get(i).getNomNetto()));
						out.print(" " + String.format(" ±%.2f%%  ", kompListe.get(i).getTolerance()));
						out.print("  0.000     ");
						out.print(" " + String.format("%.3f   ", kompListe.get(i).getNomNetto()));
						out.print(" " + String.format("%08d", kompListe.get(i).getRaavareId()));
						out.print("  LH01   ");
						out.print("   1   \n");
						out.println("\n________________________________________________________________________________\n");
					}
					
				} catch (DALException e) {
					out.println("An error occourd");
					out.println(e.getMessage());
				}
			}
		}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		ProduktBatchDTO dto;

		String data = request.getParameter("createNewBatch");

		if (data != null) {
			if (request.getParameter("receptId") != null) {
				int receptId;
				receptId = Integer.valueOf(request.getParameter("receptId"));
				dto = new ProduktBatchDTO(0, receptId, 0, null, null);
				MySQLProduktBatchDAO dao;
				try {
					dao = new MySQLProduktBatchDAO();
					dao.createProduktBatchTest(dto);
				} catch (DALException e1) {
					request.setAttribute("message",
							"Could not create object in database");
					e1.printStackTrace();
				}
			}
			request.setAttribute("message", "Batch oprettet!");
		} else {
			request.setAttribute("message", "Data var NULL...");
		}
		
		request.getRequestDispatcher("/WEB-INF/productbatch/createproductbatch.jsp").forward(request, response);
	}
}
